'use strict';
/**
 * Created by QianQi on 2017/1/19.
 */
var gulp=require('gulp');
var common = require('../common.js'),
    plugin = common.plugin,// package.json 中定义的插件
    config = common.config;// 配置
module.exports = function(opts){
    return plugin.through2.obj(function(file, encoding, callback){
        if (file.isNull()) {
            return callback(null, file);
        }
        if (file.isStream()) {
            return callback(createError(file, 'Streaming not supported'));
        }
        plugin.glob(file.path,function(err,files){
            if(err){
                callback(err);
            }
            else{
                var target=opts.target,
                    tar,
                    conf={
                        original:opts.original,
                        target:{}
                    };
                var content = file.contents.toString();
                var i=0;
                for(var name in target){
                    i++;// TODO 数量如何确定
                    tar=target[name];
                    gulp.src(tar)
                        .on('data', (function(name){
                            return function(f) {
                                conf.target[name]=f.contents;
                                content = content.replace(conf.original[name],conf.target[name]);
                                if(--i==0){
                                    file.contents = Buffer.from(content);
                                    //this.push(file);// TODO 会导致 data 回调多跑一次？？？
                                    callback(null, file);
                                }
                            }
                        })(name));
                }
            }
        });
    });
};